package org.example.order.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.common.Response;
import org.example.order.entity.OrderDO;
import org.example.order.entity.vo.AddOrderReqVO;
import org.example.order.entity.vo.OrderPageReqVO;
import org.example.order.entity.vo.UpdataOrderReqVO;
import org.example.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 订单控制层
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    private IOrderService orderService;

    /**
     * 添加订单
     * @param addOrderVO
     * @return
     */
    @PostMapping("/add")
    public Response<String> add(@RequestBody AddOrderReqVO addOrderVO) {
        try {
            OrderDO orderDO = new OrderDO();
            BeanUtils.copyProperties(addOrderVO, orderDO);
            Long orderNum = orderService.addAndGetId(orderDO);

            if (orderNum != null) {
                return Response.data(orderDO.getId().toString());
            } else {
                return Response.fail("建立订单失败");
            }
        } catch (Exception e) {
            return Response.fail("建立订单失败");
        }
    }

    /**
     * 更新订单
     * @param updataOrderReqVO
     * @return
     */
    @PostMapping("/update")
    public Response<Boolean> update(@RequestBody UpdataOrderReqVO updataOrderReqVO) {
        try {
            OrderDO orderDO = new OrderDO();
            BeanUtils.copyProperties(updataOrderReqVO, orderDO);
            boolean update = orderService.updateById(orderDO);
            if (update) {
                return Response.success(true);
            } else {
                return Response.fail("更新订单失败");
            }
        } catch (Exception e) {
            return Response.fail("更新订单失败");
        }
    }

    /**
     * 分页查询订单
     * @param orderPageVO
     * @return
     */
    @GetMapping("/page")
    public Response<Page<OrderDO>> page(OrderPageReqVO orderPageVO) {
        try {
            return Response.success(orderService.page(orderPageVO));
        } catch (Exception e) {
            return Response.fail("查询订单失败");
        }
    }

}
